from flask import Blueprint,jsonify,request
from db import db1
from utils.rs import rs
import json

bp_work = Blueprint('work',__name__)


@bp_work.route('/worklist')
def worklist():
    sql = "select * from workflow"
    res = db1.find_all(sql)
    return jsonify({'code':200,'list':res})


# 获取数据源接口
@bp_work.route('/getresourcedata',methods=['POST','GET'])
def getresourcedata():
    if request.method == 'GET':
        # 从redis取,如果有直接返回
            values = rs.get_str('dataresouce')
            if values:
                list = eval(values)
            else:
                # 如果没有查询
                sql = "select * from data_source"
                res = db1.find_all(sql)
                list = []
                if res:
                    list = eval(values)
                    for i in res:
                        dict={'id':i['id'],'name':i['name']}
                        sql1 = "select id,name,type from %s"%(i['tablename'])
                        subres = db1.find_all(sql1)
                        dict['mes'] = subres
                        list.append(dict)
                #存入redis
                rs.set_str('dataresouce',json.dumps(list))
            return jsonify({"code":200,'list':list})
    else:
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "update workflow set params='%s' where id=%d"%(data['mes'],int(data['id']))
        print(sql)
        db1.update(sql)
        res = db1.find_all(sql)
        return jsonify({"code":200})

        
@bp_work.route('/getworkf')
def getworkf():
    id = request.args.get('id')
    sql = "select * from workflow where id=%d"%(int(id))
    res = db1.find(sql)
    return jsonify({'code':200,'workf':res})


def getdeptdata(data):
    tree = {}
    list=[]
    for i in data:
        tree[i['id']] = i
    for j in data:
        pid = j['pid']
        if not pid:
            j['type']=1
            list.append(j)
        else:
            if 'children' not in tree[pid]:
                tree[pid]['children']=[]
            #查询此部门下所有员工
            sql = "select * from users where dept_id=%d"%(j['id'])
            res = db1.find_all(sql)
            userlist=[]
            if res:
                for u in res:
                    u['type'] = 3
                    userlist.append(u)
            j['children'] = userlist
            j['type']=2
            tree[pid]['children'].append(j)

    return list

@bp_work.route('/getcomanyuser')
def getcomanyuser():
    #获取所有公司及所有部门
    sql = "select * from dept"
    res = db1.find_all(sql)
    mes = getdeptdata(res)
    return jsonify({'code':200,'list':mes})
    #数据重组，查询员工
@bp_work.route('/taskm',methods=['POST'])
def taskm():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form

    title = data['title']
    params = data['params']
    auditids = data['auditids']
    #添加任务
    sql = "insert into task(title,params,next_audit,status,nexta) values('%s','%s','%s',1,%d)"%(title,params,auditids,auditids[0])
    db1.update(sql)
 
    sql1 = "select id,title from task where title='%s'"%(title)
    task = db1.find(sql1)
    #把当前任务加到redis中，选用hash类型
    key='task%d'%(auditids[0])
    rs.insert_hash(key,task['id'],task['title'])
    return jsonify({"code":200})

